from sqlalchemy.orm import Session
from db import crud, models, SessionLocal
from loguru import logger
from config import FilePath
from datetime import datetime
from .initial_data import IMAGES_FOLDER, USER_ROLE, CONFIG
import utils
import schemas
from enums import UserRoleEnum


class Boot:
    DB: Session

    def __init__(self):
        self.DB = SessionLocal()
        self.init_folder()
        logger.add(FilePath.LOG_PATH / "server.log",
                   format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{function}:{line} | {message}")
        logger.info("start init system")

        self.init_system_images_folder()
        self.init_users()
        logger.info("complete init")

        self.init_config()

        self.DB.close()

    @staticmethod
    def init_folder():
        utils.files.mkdir(FilePath.STATIC_ROOT)
        utils.files.mkdir(FilePath.ICONS)
        utils.files.mkdir(FilePath.IMAGES)
        utils.files.mkdir(FilePath.LOG_PATH)

    def init_system_images_folder(self):
        logger.info("init system images folder")

        for folder in IMAGES_FOLDER:
            if crud.ImagesFolder.get_by_name(self.DB, folder["name"]) is None:
                item = models.ImagesFolder(**folder, created_time=datetime.now())
                self.DB.add(item)
                utils.files.mkdir(FilePath.IMAGES / str(folder["id"]))
                utils.files.mkdir(FilePath.IMAGES / f"{folder['id']}/thumb")
        self.DB.commit()

    def init_users(self):
        logger.info("init users")

        for role in USER_ROLE:
            item = schemas.users.UserRoleForm(**role)
            if crud.UserRole.get(self.DB, role["id"]) is None:
                crud.UserRole.create(self.DB, item)

        # 初始化管理员
        if crud.users.Users.count(self.DB) == 0:
            user = schemas.users.UserForm(
                nickname="Admin",
                username="admin",
                roles=[UserRoleEnum.ADMIN],
                password=utils.encrypt.md5_pwd("admin"),
                created_on=datetime.now()
            )
            crud.Users.create(self.DB, user)

    def init_config(self):
        created_on = datetime.now()

        for item in CONFIG:
            if crud.Config.get_by_name(self.DB, item["name"]) is None:
                crud.Config.create(self.DB, schemas.config.CreateConfigRequest(**item, created_on=created_on))
